package com.link.base.base.email.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.email.emailutils.SendMail;
import com.link.base.base.email.model.EmailInfomation;
import com.link.base.base.email.service.EinfomationService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.util.AppConstants;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.base.core.basic.util.YmlConstants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/12 9:27
 */

@Controller
@RequestMapping("/link/emailInfo")
public class EInfomationController extends BasicController<EmailInfomation> {

    @Resource
    private AttachmentService attachmentService;
    @Resource
    private EinfomationService eInfomationService;

    @Override
    public BasicService<EmailInfomation> getBasicService() throws Exception {
        return eInfomationService;
    }

    @RequestMapping(value = "/uploadEmailAtt", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> uploadEmailAtt(EmailInfomation record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> myfiles = multipartRequest.getFiles("myfiles");
        try {
            // 插入附件表
            LCLogger.info().withMessageKey("uploadEmailAtt")
                    .withMessage(AppConstants.LOG_DIVISION_LINE + "attachment insert start!").flush();
            List<Attachment> list = attachmentService.emailAttachmentUpload(myfiles);// 附件上传，返回一个附件对象的列表
            Attachment att = list.get(0);
            result.put("success", true);
            result.put("imgFileName", att.getAttachmentName());
            result.put("result", "主题为：" + record.getEmailTitle() + "的邮件的附件已经保存成功！");
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", "主题为：" + record.getEmailTitle() + "的邮件的附件已经保存成功！");
        }
        return result;
    }

    @RequestMapping(value = "/delEmailAtt", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> delEmailAtt(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        String fileName = request.getParameter("fileName");
        try {
            //删除邮件附件
            LCLogger.info().withMessageKey("delEmailAtt")
                    .withMessage(AppConstants.LOG_DIVISION_LINE + "attachment delete start!").flush();
            attachmentService.emailAttachmentDelete(fileName);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/downloadEmailAtt/{fileName}", method = RequestMethod.GET)
    public void downloadEmailAtt(@PathVariable("fileName") String fileName, HttpSession session,
                                 HttpServletRequest request, HttpServletResponse response) {
        String extName = request.getParameter("extName");
        if (!StringUtils.isNull(fileName)) {
            String fileFullName = fileName + "." + extName;
            try {
                attachmentService.emailAttachmentDownload(fileFullName, response);
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    @RequestMapping(value = "/sendEmail", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> sendEmail(EmailInfomation record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<String, String>();

        try {
            map.put("smtp", "smtp.sina.cn");
            //邮件传输协议：如smtp
            map.put("protocol", "smtp");

            //登录邮箱的用户名
            map.put("username", "linkcrm@sina.com");
            //登录邮箱的密码
            map.put("pas", "handhand");

            //发送人的帐号
            String emailSendAddr = record.getEmailSendAddr();
            map.put("from", emailSendAddr);

            //接收人的帐号，多个以","号隔开
            String emailReceiveAddr = record.getEmailReceiveAddr();
            map.put("to", emailReceiveAddr);
            //邮件抄送人
            map.put("toCc", record.getEmailCcAddr());
            //邮件密送人
            map.put("toBCc", record.getEmailBCcAddr());
            //邮件主题
            map.put("subject", record.getEmailTitle());
            //邮件内容
            map.put("body", record.getEmailMsg());

            //内嵌了多少张图片，如果没有，则new一个不带值的Map
            Map<String, String> image = new HashMap<String, String>();
            String path = request.getRealPath("/image");
            String innerImgStr = record.getInnerImgSrc();
            if (StringUtils.isNotBlank(innerImgStr)) {
                String[] innerImgArr = innerImgStr.split("\\|");
                for (int i = 1; i <= innerImgArr.length; i++) {
                    String innerImg = innerImgArr[i - 1];
                    String imgFileName = path + "/" + innerImg.substring(innerImg.lastIndexOf("/"));
                    image.put("a0000000" + i, imgFileName);
                }
            }

            //附件的绝对路径,不发附件则new一个不带值的List
            List<String> list = new ArrayList<String>();
            String emailAtt = record.getEmailAtt();
            CoreUser user = UserUtil.getUser();
            String realativPath = "/file/" + user.getId() + "/" + "emailTemp";
            String realPath = YmlConstants.getPortalShareFileDir() + realativPath;
            if (emailAtt != null && !"".equals(emailAtt)) {
                String[] filesName = emailAtt.split("\\|");
                for (String fileName : filesName) {
                    list.add(realPath + "/" + fileName);
                }
            }

            //创建实例
            SendMail sm = new SendMail(map, list, image);
            //执行发送
            sm.send();

            result.put("success", true);
            result.put("result", "主题为：" + record.getEmailTitle() + "的邮件的附件已经保存成功！");
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
